import { GameUI } from "./GameUI.js";

class GameState {
    constructor(game) {
        this.game = game;
        this.ui = new GameUI();
        this.initGame();
        const btn = document.getElementById('playBtn');
        btn.onclick = this.startGame.bind(this);
        document.addEventListener('keydown', this.keydown.bind(this));
        document.addEventListener('keyup', this.keyup.bind(this));

    }

    showPlayBtn() {
        this.ui.show('playBtn');

    }
    startGame() {
        this.ui.showGameHud(true);
        this.game.reset();
        this.initGame();
        this.startTurn()
    }
    keydown(e) {
        if (this.state !== 'turn') return
        if (e.key === ' ') { this.ui.strengthBar.visible = true }
    }
    keyup(e) {
        if (this.state !== 'turn') return
        if (e.key === ' ') {
            this.ui.strengthBar.visible = false;
            this.hit(this.ui.strengthBar.strength)
        }

    }

    initGame() {
        this.numberedBallsOnTable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
      
        this.turn = 'player1';
        
        this.sides = {
          player1: '?',
          player2: '?'
        };
        this.poceketingOccured = false ;
        this.state = 'nostarted'
        this.ticker = null ;
    }
//  切换玩家时更新的数据
    startTurn(){ 
        if(this.state === 'gameover'){ 
            return 
        }
        this.timer = 30; // 倒计时30s
        this.tickTimer()
        this.state = 'turn' ;
        this.ui.updateTurn(this.turn );
        this.ui.updateBalls(this.numberedBallsOnTable, this.sides) ;
        const str = this.turn  === 'player1'? 'Player 1': 'Player 2';
        this.ui.log(`${str}  to play`);
    }

    whiteBallEnterHole(){
          this.ui.log(`Cue ball pocketed by${this.turn}`)  
    }
// 桌球规则
    coloredBallEnterHole(id){ 
        if(id === undefined){ 
       return 
        }
        this.numberedBallsOnTable = this.numberedBallsOnTable.fiilter((num)=> num !== id);
        if(id===0){ return };
        if(id ===8){ 
            if(this.numberedBallsOnTable.length >1){ 
                this.ui.log(`Game over ! 8 ball pocketed too early by ${this.turn}`);
                this.turn = this.turn === 'player1'?'player2':'player1'
            }
            this.poceketingOccured =true;
            this.endGame() // win
        }else { 
            if(this.sides.player1 === '?' || this.sides.player2 === '?'){ 
                this.sides[this.turn] = id< 8?'solid': 'striped';
                this.sides[this.turn === 'player1'? 'player2':'player1'] = id > 8?'solid': 'striped';
                this.poceketingOccured
            }else { 
                if(this.sides[this.turn] === 'solid' && id < 8 || this.sides[this.turn] === 'striped' && id >8){ 
                    this.poceketingOccured =true ;
                }else { 
                    this.poceketingOccured =false ;
                    this.ui.log(`${this.turn} pocked opponent's ball!`)
                }
            }

        }
    }
    // 计时器前进1s
    tickTimer(){ 
        this.ui.updateTimer(this.timer)
        if(this.timer == 0){ // timer 是剩余时间 
            this.ui.log(`${this.turn} ran out of time `) ;
            this.state ='outoftime' ;
            this.switchSides()
            const id= setTimeout(()=> { clearTimeout(id);this.tickTimer()}, 1000) ;// 为什么，这里不用timer保存呢

        }else { 
            this.timer-- ;
            clearTimeout(this.ticker); // 虽然这个定时器用了就没了但还是手动清除比较好
            this.ticker = setTimeout(this.tickTimer.bind(this),1000) ;// 隔一秒创建一个定时器 
        }
    }
//  玩家轮流
    switchSides(){
     this.turn  = this.turn  === 'player1'? 'player1': 'player2';

    }
    endGame(){
        this.state ='gameover';
        const winner  =this.turn =  'player1'? 'Player 1': 'Player 2';
        clearTimeout(this.ticker);
        this.ui.showMessage(`${winner} win !, 'thank you for playing `)

    }

    hit(strength) {
        this.game.strikeCueball(strength);
        clearTimeout(this.ticker);
        this.state = 'turnwating'
    }

    checkSleeping(){ 
        if(!this.game.cueball.isSleeping) return ;
        for(let i =1; i< this.game.balls.length;i++){ 
            if(!this.game.balls[i].isSleeping && this.numberedBallsOnTable.indexOf(Number(this.game.balls[i].name.split('ball')[0]))> -1){ 
                return 
            }
            if(!this.poceketingOccured){ this.switchSides()}
            this.poceketingOccured =false ;
            setTimeout(this.startTurn.bind(this), 1000) ;
            this.state ='paused' ;
        }
    }
    update(dt){ 
        if(this.state === 'turnwating') this.checkSleeping();
        this.ui.update()
    }

}

export {GameState}